package com.jiezheng.huinong.action;

import java.util.Map;

import com.jiezheng.huinong.biz.UserManage;
import com.jiezheng.huinong.constant.LoginFailType;
import com.jiezheng.huinong.dao.UserManageDAOImpl;
import com.jiezheng.huinong.model.UserInfo;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 5565689892551475654L;

	private UserInfo user = new UserInfo();
	private String passwordNew = "";
	private LoginFailType loginError = LoginFailType.PASSWORD_ERROR;

	/**
	 * 实现登录
	 */

	public String login() {
		return SUCCESS;
	}

	/**
	 * 实现登录 JSON接口
	 */
	public String loginCheck() {

		/**
		 * 检查用户权限
		 */
		LoginFailType ret = UserManage.checkUser(user);
		if (ret == LoginFailType.LOGIN_SUCCESS) {
			UserInfo userIn = (new UserManageDAOImpl()).getUserByLoginId(user
					.getLoginId());

			// 加入session记录
			Map<String, Object> session = ActionContext.getContext()
					.getSession();
			session.put("loginId", userIn.getLoginId());
			session.put("user", userIn.getName());
			session.put("dept", userIn.getDept());
			session.put("post", userIn.getPost());
			session.put("deptNo", userIn.getDeptNo());
			session.put("postNo", userIn.getPostNo());
			this.setLoginError(LoginFailType.LOGIN_SUCCESS);
		}

		this.setLoginError(ret);

		return SUCCESS;

	}

	/**
	 * 退出登录
	 * 
	 * @return
	 */
	public String loginOut() {
		Map<String, Object> session = ActionContext.getContext().getSession();
		session.remove("loginId");
		session.remove("user");
		session.remove("dept");
		session.remove("post");
		session.remove("deptNo");
		session.remove("postNo");
		return LOGIN;
	}

	/**
	 * 修改账户信息，并退出登录
	 * 
	 * @return
	 */
	public String accountModify() {

		// 检查用户权限
		LoginFailType ret = UserManage.checkUser(user);
		if (ret == LoginFailType.LOGIN_SUCCESS) {

			// 修改账户密码
			user.setPassword(passwordNew);
			(new UserManageDAOImpl()).modifyUserAccount(user);

			Map<String, Object> session = ActionContext.getContext()
					.getSession();
			session.remove("loginId");
			session.remove("user");
			session.remove("dept");
			session.remove("post");
			session.remove("deptNo");
			session.remove("postNo");
			this.setLoginError(ret);
		}
		this.setLoginError(ret);
		return SUCCESS;
	}


	public LoginFailType getLoginError() {
		return loginError;
	}

	public void setLoginError(LoginFailType loginError) {
		this.loginError = loginError;
	}

	public String getPasswordNew() {
		return passwordNew;
	}

	public void setPasswordNew(String passwordNew) {
		this.passwordNew = passwordNew;
	}

	public UserInfo getUser() {
		return user;
	}

	public void setUser(UserInfo user) {
		this.user = user;
	}

}
